package cn.itsource.basic.service.impl;

import cn.itsource.basic.domain.dto.LoginDto;
import cn.itsource.basic.exception.CustomException;
import cn.itsource.basic.service.ILoginService;
import cn.itsource.basic.util.MD5Utils;
import cn.itsource.user.domain.Logininfo;
import cn.itsource.user.mapper.LogininfoMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

@Service
public class LoginServiceImpl implements ILoginService {

    @Autowired
    private LogininfoMapper logininfoMapper;

    @Autowired
    private RedisTemplate redisTemplate;

    @Override
    public Object accountLogin(LoginDto dto) {
        //非空校验
        if(StringUtils.isEmpty(dto.getUsername()) || StringUtils.isEmpty(dto.getPassword())){
            throw new CustomException("参数异常");
        }
        //查询是否有这个用户
        Logininfo logininfo = logininfoMapper.queryByUserNameAndType(dto.getUsername(),dto.getType());

        if(logininfo == null){
            throw new CustomException("该用户不存在");
        }
        //通过传进来的密码进行加密后和查询出来的密码比对
        String newPassword = MD5Utils.encrypByMd5(dto.getPassword() + logininfo.getSalt());

        if(!logininfo.getPassword().equals(newPassword)){
            throw new CustomException("用户名或密码错误");
        }
        //生成UUID存储到redis，key是uuid，value是loginInfo对象，过期时间30分钟
        String token = UUID.randomUUID().toString();

        redisTemplate.opsForValue().set(token,logininfo,30, TimeUnit.MINUTES);
        //返回给前端，UUID，loginInfo
        Map<String, Object> map = new HashMap<>();
        map.put("token",token);
        logininfo.setSalt(null);
        logininfo.setPassword(null);
        map.put("logininfo",logininfo);

        return map;
    }
}
